﻿using System.Linq;
using System.Web.Mvc;
using Safal.IncidentTracker.Domain.Abstract;
using Safal.IncidentTracker.Domain.Entities;
using Safal.IncidentTracker.WebUI.HtmlHelpers;

namespace Safal.IncidentTracker.WebUI.Controllers
{
    public class IncidentsController : Controller
    {
        private readonly IIncidentsRepository _incidentsRepository;
        public int PageSize { private get; set; }

        public IncidentsController(IIncidentsRepository incidentsRepository)
        {
            _incidentsRepository = incidentsRepository;
            PageSize = 8;
        }
        public ViewResult List(int page = 1)
        {
            var incidents = new PagedList<Incident>(_incidentsRepository.Incidents, page - 1, PageSize);
            return View(incidents);
        }

        public ActionResult Edit(int id)
        {
            var incident = _incidentsRepository.Incidents
                .Where(j => j.Id == id)
                .FirstOrDefault();
            if (incident == null)
            {
                TempData["ErrorMessage"] = "Cannot Find incident";
                return RedirectToAction("List", new { page = 1 });
            }

            return View(incident);
        }

        [HttpPost]
        public ActionResult Edit(Incident updatedIncident)
        {
            Incident incident = (updatedIncident.Id == 0) ?
                new Incident() :
                _incidentsRepository.Incidents.First(j => j.Id == updatedIncident.Id);

            TryUpdateModel(incident);

            if (ModelState.IsValid)
            {
                _incidentsRepository.SaveIncident(incident);
                return RedirectToAction("List", new { page = 1 });
            }

            return View(updatedIncident);
        }


        public ViewResult Create()
        {
            return View("Edit", new Incident());
        }

        public ActionResult Delete(int jobId)
        {
            Incident incident = _incidentsRepository.Incidents.
                Where(j => j.Id == jobId)
                .FirstOrDefault();

            if (incident == null)
            {
                TempData["ErrorMessage"] = "Cannot Find incident";
                return RedirectToAction("List", new { page = 1 });
            }
            TempData["ErrorMessage"] = "incident '" + incident.Title + "' deleted.";
            _incidentsRepository.DeleteIncident(incident);

            return RedirectToAction("List", new { page = 1 });
        }
    }
}
